﻿using System;
using System.IO;
using System.Text;
using System.Threading;
using Kugar.Core.ExtMethod;
using Kugar.Core.Network;
using Newtonsoft.Json.Linq;
using Yahoo.Yui.Compressor;

namespace Kugar.Tools.CityTool.ReadTencentMapCityInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("开始抓取腾讯数据,请输入地图Key");

            var key = Console.ReadLine().ToStringEx().Trim();

            Console.WriteLine("开始抓取");

            var result=WebHelper.Create($"https://apis.map.qq.com/ws/district/v1/list?key={key}")
                .Get_JsonAsync().Result
                ;

            var data_version = result.GetString("data_version");

            Console.WriteLine("data_version=" + data_version);

            var data = new JArray();

            var provinces = result.GetJArray("result")[0] as JArray;

            foreach (JObject province in provinces)
            {
                var provinceID = province.GetString("id");

                var result_ProvinceJson=new JObject()
                {
                    ["code"]= provinceID,
                    ["name"]=province.GetString("fullname"),
                    ["shortname"] = province.GetString("name")
                };

                Console.WriteLine($"正在抓取{result_ProvinceJson.GetString("name")}");

                data.Add(result_ProvinceJson);


                var cities = getNextLevel(provinceID, key);

                var firstCityID = (cities.First as JObject).GetString("code");

                if (firstCityID.Right(2)!="00") //如果是直辖市,会取到区一级,,末尾不为0
                {
                    var tmp = new JObject() //直接添加一个市名字
                    {
                        ["code"] = firstCityID.Left(4) + "00",
                        ["name"] = province.GetString("fullname"),
                        ["shortname"] = province.GetString("name"),
                    };

                    result_ProvinceJson.Add("sub",new JArray()
                    {
                        tmp
                    });

                    tmp.Add("sub", cities);
                }
                else
                {
                    result_ProvinceJson.Add("sub",cities);

                    foreach (JObject city in cities)
                    {
                        var districts = getNextLevel(city.GetString("code"), key);

                        if (districts.Count==1) //如果没有区的,比如中山,则读取镇一级
                        {
                            var town = getNextLevel((districts.First as JObject).GetString("code"), key);

                            city.Add("sub",town);
                        }
                        else
                        {
                            
                            city.Add("sub", districts);
                        }
                    }
                }
            }

            if (File.Exists("city.json"))
            {
                File.Delete("city.json");
            }

            if (File.Exists("city.min.json"))
            {
                File.Delete("city.min.json");
            }

            var resultStr = data.ToStringEx();
            File.WriteAllBytes("city.json",Encoding.UTF8.GetBytes(resultStr));

            var c = new JavaScriptCompressor();

            var minferFile = c.Compress(resultStr);

            File.WriteAllBytes("city.min.json", Encoding.UTF8.GetBytes(minferFile));


            Console.WriteLine("抓取完成,已存放在当前目录下的city.json文件");

            Console.ReadLine();
        }

        private static JArray getNextLevel(string parentID, string key)
        {
            Thread.Sleep(300);

            var json =
                    WebHelper.Create($"https://apis.map.qq.com/ws/district/v1/getchildren?id={parentID}&key={key}")
                        .Get_JsonAsync().Result
                        
                ;

            var cities = json.GetJArray("result")[0];

            var jarray = new JArray();

            foreach (JObject city in cities)
            {
                var shortName = city.GetString("name");

                var result_City = new JObject()
                {
                    ["code"] = city.GetString("id"),
                    ["name"] = city.GetString("fullname"),
                    ["shortname"] = string.IsNullOrWhiteSpace(shortName)?city.GetString("fullname"):shortName
                };

                jarray.Add(result_City);
            }

            return jarray;
        }
    }
}
